package java8._06_使用流收集数据;

import org.junit.Test;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class _01_groupbBy {


    enum Type {
        Chinese,
        Math,
        English;
    }

    static class Book {

        public Type type;
        public String name;
        public int price = (int) (Math.random() * 10);

        public Book(Type type, String name) {
            this.type = type;
            this.name = name;
        }

        @Override
        public String toString() {
            return type + "==" + name;
        }
    }

    @Test
    public void testGroupBy() {
        ArrayList<Book> books = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            books.add(new Book(Type.Chinese, Type.Chinese + "" + i));
        }
        for (int i = 0; i < 5; i++) {
            books.add(new Book(Type.Math, Type.Math + "" + i));
        }
        for (int i = 0; i < 5; i++) {
            books.add(new Book(Type.English, Type.English + "" + i));
        }

        Book collect = books.stream().collect(
            Collectors.collectingAndThen(
                Collectors.maxBy(Comparator.comparing(item -> item.type)),
                Optional::get)
        );


        Map<Type, Integer> collect1 = books.stream().collect(
            Collectors.groupingBy(item -> item.type
                , Collectors.summingInt(item -> item.price))

        );

        Map<Type, Integer> collect2 = books.stream().collect(
            Collectors.groupingBy(item -> item.type,
                Collectors.mapping(item -> item.price,
                    Collectors.summingInt(item -> item)))
        );
        ArrayList<Book> collect3 = books.stream().collect(Collectors.toCollection(ArrayList::new));
        Collectors.toList();
        Collectors.toSet();


        //分区
        books.stream().collect(
            Collectors.partitioningBy(item -> item.type.equals(Type.Chinese))
        );


    }
}
